const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLList,
  GraphQLNonNull
} = require('graphql')

const axios = require('axios')

const CommentType = new GraphQLObjectType({
  name: 'CommentType',
  fields: {
    id: {
      type: GraphQLInt
    },
    content: {
      type: GraphQLString
    }
  }
})

const TheaterType = new GraphQLObjectType({
  name: 'TheaterType',
  fields: {
    id: {
      type: GraphQLInt,
    },
    name: {
      type: GraphQLString
    }
  }
})

const MovieType = new GraphQLObjectType({
  name: 'MovieType',
  fields: {
    id: {
      type: GraphQLInt
    },
    title: {
      type: GraphQLString
    },
    genres: {
      type: GraphQLString,
    },
    rating: {
      type: GraphQLFloat,
    },
    theater: {
      type: new GraphQLList(TheaterType),
      async resolve(obj) {
        let ids = obj.theater.join('|')
        let result = await axios.get(`http://localhost:9000/theaters?id_like=(${ids})`)
        return result.data
      }
    },
    comments: {
      type: new GraphQLList(CommentType),
      async resolve(obj) {
        let result = await axios.get(`http://localhost:9000/comments?theaters=${obj.id}`)
        return result.data
      }
    }
  }
})

const RootQueryType = new GraphQLObjectType({
  name: 'rootQueryType',
  fields: {
    hello: {
      type: GraphQLString,
      resolve() {
        return 'world'
      }
    },

    movie: {
      type: MovieType,
      args: {
        id: {
          type: new GraphQLNonNull(GraphQLInt)
        }
      },
      async resolve(obj, args) {
        let result = await axios.get(`http://localhost:9000/subjects/${args.id}`)
        return result.data
      }
    },

    movies: {
      type: new GraphQLList(MovieType),
      async resolve() {
        let result = await axios.get('http://localhost:9000/subjects')
        return result.data
      }
    }
  }
})

module.exports = RootQueryType